<template>
  <!-- 添加质量例会 -->
  <base-breadcrumb>
    <a-spin :spinning="loading">
      <a-card>
        <title-name title="会议发起" />
        <custom-form
          ref="form"
          :is-validate="true"
          :edit-model="''"
          :rules="rules"
          :form="form"
          :form-list="formOption"
          @selectOrg="selectOrg"
        >
          <template slot="speakerId">
            <SelectPersonByProject
              :id="form.branchComId"
              v-model="form.speakerId"
              :project-id="form.projectId"
              :show-search="true"
              mode="combobox"
              placeholder="请选择"
              option-label-prop="children"
            />
          </template>
          <template slot="meetingTime">
            <a-date-picker
              v-model="form.meetingTime"
              :show-time="{ format: 'HH:mm' }"
              format="YYYY-MM-DD HH:mm"
              placeholder="请选择"
            />
          </template>
        </custom-form>
      </a-card>
      <a-card>
        <title-name title="参会人员" />
        <a-form-model-item
          label="参会者选择："
          prop="meetingEmployeeDTOList"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
        >
          <!-- 操作 -->
          <div class="mb12">
            <a-button icon="plus" class="btn_right" type="primary" @click="visible = true"> 添加人员 </a-button>
            <a-button icon="delete" type="danger" :disabled="form.employeeList.length < 1" @click="handleRemoveMore">
              移除
            </a-button>
          </div>
          <!-- 操作 -->
          <!-- 统计选中项 -->
          <a-alert :show-icon="true">
            <template slot="message">
              <span style="margin-right: 12px">
                已选择:
                <a>
                  <b>{{ selectedRowKeys.length }}</b>
                </a>
                项
              </span>
            </template>
          </a-alert>
          <!-- 统计选中项 -->
          <!-- 表格 -->
          <s-table
            ref="tableEmployee"
            table-layout="fixed"
            size="default"
            row-key="id"
            :columns="columns"
            :data="loadData"
            :alert="true"
            :row-selection="rowSelection"
            show-size-changer
            show-quick-jumper
            show-pagination="auto"
          >
            <span slot="actions" slot-scope="text, record, index">
              <template>
                <a @click="handleRemove(index)">移除</a>
              </template>
            </span>
          </s-table>
          <!-- 表格 -->
        </a-form-model-item>
      </a-card>
      <div class="tool-btns page-btn-right-top">
        <a-button class="ml20" :loading="submitLoading" type="primary" @click="handleSubmit"> 提交 </a-button>
        <a-button class="ml20" @click="handleClose"> 关闭 </a-button>
      </div>
      <!-- 添加人员模态框 -->
      <dialog-edit
        ref="dialogEdit"
        :meeting-employee-d-t-o-list-data="form.employeeList"
        :visible.sync="visible"
        @confirm="addEmployee"
        @confirms="addEmployees"
      />
      <!-- 添加人员模态框 -->
    </a-spin>
  </base-breadcrumb>
</template>
<script>
import { columnsEmployee, btnPermission } from './model.js'
import SelectSubCompany from '@/components/Select/SelectSubCompany'
import SelectProject from '@/components/Select/SelectProject'
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import dialogEdit from '@/views/conference/standardConference/conferenceList/dialogEdit.vue'
import training from '@/api/design/training'
import { getAuditProject } from '@/api/themeChoose/themeChoose'
export default {
  name: 'a' + Date.now(),
  components: {
    dialogEdit,
    SelectPersonByProject
  },
  data() {
    return {
      // 页面加载
      loading: false,
      // 表单
      form: {
        meetingType: '7',
        employeeList: [],
        projectDesignType: ''
      },
      // 表格选中项
      selectedRowKeys: [],
      // 表格复选
      rowSelection: {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys) => {
          this.selectedRowKeys = selectedRowKeys
        }
      },
      // 表头
      columns: columnsEmployee,
      // 添加人员模态框显示隐藏
      visible: false,
      // 提交loading
      submitLoading: false,
      // 项目设计管理类别
      designType: {},
      // 按钮权限
      btnPermission
    }
  },
  computed: {
    // 表单配置
    formOption() {
      const list = [
        {
          label: '会议类型',
          keyName: 'meetingType',
          type: 'a-select',
          data: [
            {
              label: '质量周例会',
              value: '6'
            },
            {
              label: '质量专项检查会',
              value: '7'
            },
            {
              label: '其他',
              value: '8'
            }
          ],
          rules: [{ required: true, message: '请选择会议类型', trigger: 'change' }]
        },
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst: true,
          isNeedAuth:true ,
          checkStrictly: true,
          // disabled: this.editModel == 0,
          // isNoBorder: this.editModel == 0,
          // viewName: "viewName",
        },
        // {
        //   label: '所属分公司',
        //   keyName: 'branchComId',
        //   type: SelectSubCompany,
        //   attrs: {
        //     //表单项关联
        //     autoSelected: true
        //   },
        //   rules: [{ required: true, message: '请选择', trigger: 'change' }]
        // },
        // {
        //   label: '所属项目',
        //   keyName: 'projectId',
        //   type: SelectProject,
        //   attrs: {
        //     //表单项关联
        //     autoSelected: true,
        //     keyValue: 'branchComId',
        //     isEdit: true,
        //     form: this.form
        //   },
        //   rules: [{ required: true, message: '请选择', trigger: 'change' }]
        // },
        {
          label: '会议名称',
          keyName: 'meetingName',
          type: 'BaseInput',
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        {
          label: '主持人/主讲人',
          keyName: 'speakerId',
          slot: true,
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        {
          label: '会议时间',
          keyName: 'meetingTime',
          slot: true,
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          label: '会议地点',
          keyName: 'meetingPlace',
          type: 'BaseInput',
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        {
          label: '会议说明',
          keyName: 'meetingExplain',
          type: 'BaseTextarea',
          attrs: {
            maxLength: 1000
          },
          rules: [{ required: true, message: '请输入', trigger: 'change' }],
          span: 24
        }
      ]
      return list
    },
    // 校验
    rules() {
      const obj = {}
      this.formOption.map((item) => {
        if (item.rules) {
          obj[item.keyName] = item.rules
        }
      })
      return obj
    }
  },
  watch: {
    'form.projectId': {
      handler(val) {
        this.getDesignType(val)
      }
    }
  },
  methods: {
    selectOrg(val){
      this.form.branchComId = val[val.length-2].orgId
      },
    /**
     * @description: 表格数据加载方法
     * @param {Object} parameter 分页信息
     * @return {Promise} 接口Promise
     */
    loadData(parameter) {
      const vm = this
      try {
        return new Promise((resolve, reject) => {
          let obj = {}
          obj.currentPage = parameter.pageNo
          obj.pageSize = parameter.pageSize
          obj.totalPage = Math.ceil(vm.form.employeeList.length / parameter.pageSize)
          obj.totalSize = vm.form.employeeList.length
          obj.data = vm.form.employeeList || []
          resolve(obj)
        })
      } catch (error) {
        console.log(error)
      }
    },
    /**
     * @description: 获取项目设计管理类别
     * @param {*}
     * @return {*}
     */
    async getDesignType(val) {
      try {
        const { data } = await getAuditProject({
          projectId: val,
          branchComIds: [this.form.branchComId]
        })
        this.designType = {
          designTypeId: data[0]?.designTypeId || undefined,
          designTypeName: data[0]?.designTypeName || undefined
        }
        this.form.projectDesignType = this.designType.designTypeName
      } catch (error) {
        console.log(error)
      }
    },
    /**
     * @description: 人员表单单个添加
     * @param {object} e 人员
     * @return {Void}
     */
    addEmployee(e) {
      this.form.employeeList.push(e)
      this.$refs.tableEmployee.refresh(true)
    },
    /**
     * @description: 人员表单多个添加
     * @param {array} e 人员列表
     * @return {Void}
     */
    addEmployees(e) {
      e.forEach((item) => {
        this.form.employeeList.push(item)
      })
      this.$refs.tableEmployee.refresh(true)
    },
    /**
     * @description: 移除人员选中项
     * @param {void}
     * @return {void}
     */
    handleRemoveMore() {
      // 若有选中项
      let that = this
      that.$confirm({
        title: '温馨提示',
        content: '确定移除这些数据？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          for (let index = 0; index < that.form.employeeList.length; index++) {
            let item = that.form.employeeList[index]
            if (that.selectedRowKeys.includes(item.id)) {
              that.form.employeeList.splice(index, 1)
              index--
            }
          }
          that.$refs.tableEmployee.clearSelected()
          that.$refs.tableEmployee.refresh(true)
        }
      })
    },
    /**
     * @description: 移除人员
     * @param {number} index
     * @return {void}
     */
    handleRemove(index) {
      this.form.employeeList.splice(index, 1)
      this.$refs.tableEmployee.refresh(true)
    },
    /**
     * @description: 提交
     * @param {void}
     * @return {void}
     */
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.employeeList.length > 0) {
            this.submitLoading = true
            const form = this.$clone(this.form)
            form.employeeList = form.employeeList.map((el) => {
              return {
                userId: el.userId
              }
            })
            form.meetingTypeName = {
              6: '质量周例会',
              7: '质量专项检查会',
              8: '其他'
            }[form.meetingType]
            form.qualityMeeting = 1
            form.meetingTime = form.meetingTime.format('YYYY-MM-DD HH:mm')
            training
              .insertSelective(form)
              .then(({ code, message }) => {
                if (code === 200) {
                  this.$message.success('新增成功')
                  this.handleClose()
                } else {
                  this.$message.warning(message)
                }
              })
              .finally(() => {
                this.submitLoading = false
              })
          } else {
            this.$message.warning('请选择参会人员')
          }
        }
      })
    },
    /**
     * @description: 关闭
     * @param {void}
     * @return {void}
     */
    handleClose() {
      this.$multiTab.close(this.$route.fullpath)
    }
  }
}
</script>
<style lang="less" scoped>
</style>
